package com.qd.qx.ui.module2;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextPaint;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aspsine.irecyclerview.IRecyclerView;
import com.aspsine.irecyclerview.animation.ScaleInAnimation;
import com.aspsine.irecyclerview.universaladapter.ViewHolderHelper;
import com.aspsine.irecyclerview.universaladapter.recyclerview.CommonRecycleViewAdapter;
import com.qd.common.base.BaseActivity;
import com.qd.common.baserx.RxSubscriber;
import com.qd.common.commonutils.ImageLoaderUtils;
import com.qd.common.commonutils.JsonUtils;
import com.qd.common.commonutils.ToastUitl;
import com.qd.qx.R;
import com.qd.qx.api.Api;
import com.qd.qx.bean.MessageInfoBean;
import com.qd.qx.bean.SelectPathBean;
import com.qd.qx.bean.TongXunLuLocalBean;
import com.qd.qx.bean.TongxunluBean;
import com.qd.qx.ui.module1.SearchActivity;
import com.qd.chatui.util.MyUtils;
import com.qd.qx.widget.NineGridImageViewAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Code is far away from bug with the animal protecting
 * Author：YS on 2018/10/29
 * Function：通讯录子集activity
 */
public class TongxunluChildActivity extends BaseActivity {
    @BindView(R.id.ivBack)
    ImageView ivBack;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvMore)
    TextView tvMore;
    @BindView(R.id.ivMore)
    ImageView ivMore;
    @BindView(R.id.rlSearch)
    RelativeLayout rlSearch;
    @BindView(R.id.txlChildIrcv)
    IRecyclerView txlChildIrcv;
    @BindView(R.id.ircv_path)
    RecyclerView ircvPath;
    List<TongXunLuLocalBean> list = new ArrayList<>();
    String dpId;//部门编号
    String dpName;//部门名称
    CommonRecycleViewAdapter itemAdapter;
    CommonRecycleViewAdapter pathAdapter;
    List<SelectPathBean> pathList = new ArrayList<>();//路径集合
    private String leaderTag = "";//返回的数据第一个是leader 做个记录

    /**
     * 入口
     *
     * @param activity
     */
    public static void startAction(Activity activity, String dpId, String dpName) {
        Intent intent = new Intent(activity, TongxunluChildActivity.class);
        intent.putExtra("dpId", dpId);
        intent.putExtra("dpName", dpName);
        intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        activity.startActivity(intent);
        activity.overridePendingTransition(R.anim.fade_in,
                com.qd.common.R.anim.fade_out);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_tongxunlu_child;
    }

    @Override
    public void initPresenter() {

    }

    @Override
    protected void onNewIntent(Intent intent) {
        setData(intent);//新来的intent
        refreshActivty();
        super.onNewIntent(intent);
    }

    @Override
    public void initView() {
        ivMore.setVisibility(View.GONE);
        setData(getIntent());
        initAdapter();
        initPathAdapter();
        requestAction();
    }

    private void setData(Intent intent) {
        dpId = intent.getStringExtra("dpId");
        if (TextUtils.isEmpty(dpId)) {
            dpId = "0";
        }
        dpName = intent.getStringExtra("dpName");
        tvTitle.setText(dpName);
        clearPathList();

    }

    private void clearPathList() {
        if (isLocalHave()) {
            List<SelectPathBean> newList = new ArrayList<>();
            for (SelectPathBean bean : pathList) {
                newList.add(bean);
                if (dpId.equals(bean.getDpId())) {
                    break;
                }
            }
            pathList.clear();
            pathList.addAll(newList);
        } else {
            pathList.add(new SelectPathBean(dpId, dpName));
        }

    }

    private boolean isLocalHave() {
        for (SelectPathBean bean : pathList) {
            if (dpId.equals(bean.getDpId())) {
                return true;
            }
        }
        return false;
    }

    private void refreshActivty() {
        requestAction();
        if (null != itemAdapter) {
            itemAdapter.notifyDataSetChanged();
        }
        if (null != pathAdapter) {
            pathAdapter.replaceAll(pathList);
            pathAdapter.notifyDataSetChanged();
        }
    }

    private void initAdapter() {
        itemAdapter = new CommonRecycleViewAdapter<TongXunLuLocalBean>(this, R.layout.txl_ircv_itemlayout) {
            @Override
            public void convert(ViewHolderHelper helper, final TongXunLuLocalBean bean) {
                ImageView imageView = helper.getView(R.id.ivHeader);
                TextView tvName = helper.getView(R.id.tvName);
                TextView tvLeader = helper.getView(R.id.tvLeader);
                TextView tvAllCount = helper.getView(R.id.tvAllCount);
                ImageView ivLeader = helper.getView(R.id.ivLeader);
                //0为人  1位部门
                if (0 == bean.getType()) {
                    tvName.setText(bean.getName());
                    tvLeader.setText("");
                    tvAllCount.setText("");
                    MyUtils.displayUserHeader(TongxunluChildActivity.this, imageView, bean.getHeadImg(), bean.getName());
                    if (leaderTag.equals(bean.getAccount())) {
                        ivLeader.setVisibility(View.VISIBLE);
                    } else {
                        ivLeader.setVisibility(View.GONE);
                    }
                }

                if (1 == bean.getType()) {
                    ImageLoaderUtils.displayRound(TongxunluChildActivity.this, imageView, bean.getDeptHeadImg());
                    tvName.setText(bean.getDeptName());
                    //   tvLeader.setText("(负责人： " + bean.getLeader() + ")");
                    // tvAllCount.setText(bean.getTotalPeople() + "");
                }

                helper.getConvertView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (0 == bean.getType()) {
                            PeopleInfoActivity.startAction(TongxunluChildActivity.this, bean.getAccount());
                        } else if (1 == bean.getType()) {
                            TongxunluChildActivity.startAction(TongxunluChildActivity.this, bean.getDeptid(), bean.getDeptName());
                        }


                    }
                });
            }
        };
        txlChildIrcv.setLayoutManager(new LinearLayoutManager(TongxunluChildActivity.this));
        itemAdapter.addAll(list);
        itemAdapter.openLoadAnimation(new ScaleInAnimation());
        txlChildIrcv.setAdapter(itemAdapter);
    }

    private void requestAction() {
        Map<String, String> map = new HashMap<>();
        map.put("deptid", dpId);
        mRxManager.add((Api.getDefault().requestTongXunLu(Api.newRequestBody(map)))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxSubscriber<MessageInfoBean>(TongxunluChildActivity.this, false) {
                    @Override
                    protected void _onNext(MessageInfoBean messageInfoBean) {
                        TongxunluBean tongxunluBean = (TongxunluBean) JsonUtils.ObjectToBean(messageInfoBean.getData(), TongxunluBean.class);
                        if (null == messageInfoBean) {
                            ToastUitl.showShort("数据有误");
                            return;
                        }
                        parseData(tongxunluBean);
                    }

                    @Override
                    protected void _onError(String message) {
                        ToastUitl.showShort("请求失败" + message);
                    }
                }));

    }

    /**
     * 解析数据到本地集合
     *
     * @param tongxunluBean
     */
    private void parseData(TongxunluBean tongxunluBean) {
        //解析数据到本地集合
        List<TongxunluBean.PeopleListBean> peopleListBeans = tongxunluBean.getPeopleList();
        TongXunLuLocalBean tongXunLuLocalBean = null;
        list.clear();
        if (null != peopleListBeans) {
            if (0 != peopleListBeans.size()) {
                leaderTag = peopleListBeans.get(0).getAccount();//leader的账号记录下来
            }
            for (TongxunluBean.PeopleListBean bean : peopleListBeans) {
                tongXunLuLocalBean = new TongXunLuLocalBean();
                tongXunLuLocalBean.setType(0);
                tongXunLuLocalBean.setAccount(bean.getAccount());
                tongXunLuLocalBean.setName(bean.getName());
                tongXunLuLocalBean.setDeptName(bean.getDeptName());
                tongXunLuLocalBean.setPositionName(bean.getPositionName());
                tongXunLuLocalBean.setRefCode(bean.getRefCode());
                tongXunLuLocalBean.setEmali(bean.getEmali());
                tongXunLuLocalBean.setPhone(bean.getPhone());
                tongXunLuLocalBean.setSex(bean.getSex());
                tongXunLuLocalBean.setManagerName(bean.getManagerName());
                tongXunLuLocalBean.setHeadImg(bean.getHeadImg());
                list.add(tongXunLuLocalBean);
            }
        }
        List<TongxunluBean.DeptListBean> deptListBeans = tongxunluBean.getDeptList();
        if (null != deptListBeans) {
            for (TongxunluBean.DeptListBean bean : deptListBeans) {
                tongXunLuLocalBean = new TongXunLuLocalBean();
                tongXunLuLocalBean.setType(1);
                tongXunLuLocalBean.setDeptid(bean.getDeptid());
                tongXunLuLocalBean.setDeptName(bean.getDeptName());
                tongXunLuLocalBean.setLeader(bean.getLeader());
                tongXunLuLocalBean.setTotalPeople(bean.getTotalPeople());
                tongXunLuLocalBean.setDeptHeadImg(bean.getDeptHeadImg());
                list.add(tongXunLuLocalBean);
            }
        }
        itemAdapter.replaceAll(list);
        itemAdapter.notifyDataSetChanged();
    }

    /**
     * 头像9宫格适配器
     */
    private NineGridImageViewAdapter<String> nineGridImageViewAdapter = new NineGridImageViewAdapter<String>() {
        @Override
        protected void onDisplayImage(Context context, ImageView imageView, String photo) {
            ImageLoaderUtils.displaySmallRound(TongxunluChildActivity.this, imageView, photo);
        }

        @Override
        protected ImageView generateImageView(Context context) {
            return super.generateImageView(context);
        }
    };

    /**
     * 路径adapter
     */
    private void initPathAdapter() {
        pathAdapter = new CommonRecycleViewAdapter<SelectPathBean>(TongxunluChildActivity.this, R.layout.item_path_select_layout) {
            @Override
            public void convert(ViewHolderHelper helper, final SelectPathBean bean) {
                TextView textView = helper.getView(R.id.tvPath);
                textView.setText(bean.getDpName());
                if (bean.getDpId().equals(dpId)) {
                    textView.setCompoundDrawables(null, null, null, null);
                    TextPaint tp = textView.getPaint();
                    tp.setFakeBoldText(true);
                } else {
                    Drawable drawable = TongxunluChildActivity.this.getResources().getDrawable(R.drawable
                            .youjiantou);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    textView.setCompoundDrawables(null, null, drawable, null);
                    TextPaint tp = textView.getPaint();
                    tp.setFakeBoldText(false);
                }
                textView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        TongxunluChildActivity.startAction(TongxunluChildActivity.this, bean.getDpId(), bean.getDpName());
                    }
                });
            }
        };
        ircvPath.setLayoutManager(new
                LinearLayoutManager(TongxunluChildActivity.this, LinearLayoutManager.HORIZONTAL, false));
        pathAdapter.addAll(pathList);
        ircvPath.setAdapter(pathAdapter);
    }

    @OnClick({R.id.ivBack, R.id.ivMore, R.id.rlSearch})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ivBack:
                finish();
                break;
            case R.id.ivMore:

                break;
            case R.id.rlSearch:
                SearchActivity.startAction(this);
                break;
        }
    }
}
